import csv
#原始数据文件去掉一些项目！！！
with open(r'data1.csv','r',encoding='utf-8') as f:
    #str=f.read()
    #print(str)
    lt=f.readlines()
    print(lt[0])
    print(type(lt[0]))
    lt[0]=lt[0].replace(', ,',',')
    lt[0]=lt[0].replace('操作,','查看,往期,')
    lt[0] = lt[0].replace('全选,序号,查看,往期,', '序号,')
    lt[0]=lt[0].replace(r'[201-1] 行业代码(GB/T4754-2017)','行业代码')
    lt[0] = lt[0].replace('期别(年)', '期别年')
    lt[0] = lt[0].replace('期别(月)', '期别月')
    lt[0]=lt[0].replace(',\n','')
    lt[0] = lt[0].replace(r';', '')
    lt[0] = lt[0].replace(r'1-本月', '本期')
    lt[0] = lt[0].replace('(损失以“-”号记)', '')
    # lt[0] = lt[0].replace('本期资产处置收益(损失以“-”号记)千元','本期资产处置收益千元')
    # lt[0] = lt[0].replace('上年同期资产处置收益(损失以“-”号记)千元', '上年同期资产处置收益千元')
    print(lt[0])
    print('#'*30)
    print(lt)
    ltlist=lt[0].split(',')
    print(ltlist)
    print(ltlist[0])
    print(type(ltlist[0]))
    print('#'*30)
    listlen=len(ltlist)
    print(len(ltlist))

#C:\Users\hsk\PycharmProjects\vdcode\
#with open(r'data1.csv','w',encoding='utf-8') as f:
#    f.writelines(lt[0])
    #f.write(lt)
file = open('data1.csv',encoding='utf-8')
rd = csv.DictReader(file)
print(rd)
print(type(rd))

#for row in rd:
#    print(row['数据处理地'],row['行业代码'],row['期别(年)'],row['期别(月)'],row['单位详细名称'],row['本期营收'],row['上期营收'],row['营业收入增速'])

with open('data2.csv','w',encoding='utf-8') as f:
    f.write(lt[0])
    f.write(',\n')
    print('*'*30)
    print(lt[0])


    for row in rd:
        for i in range(len(ltlist)):
            f.write(row[ltlist[i]]+',')
        #f.write(row[ltlist[listlen]])
        #f.write(row['数据处理地'] + ',' + row['行业代码'] + ',' + row['期别(年)'] + ',' + row['期别(月)'] + ',' + row['单位详细名称'] + ',' +
        #        row['组织机构代码'] + ',' + row['当月1'] + ',' + row['同期当月'] + ',' + row['当月增速'])
        f.write('\n')


#'数据处理地,行业代码,期别年,期别月,单位详细名称,组织机构代码,本期,上期,增速'
#row[ltlist[0]]+','+row[ltlist[1]]+','+row[ltlist[2]]+','+row[ltlist[3]]+','+row[ltlist[4]]+','+row[ltlist[5]]+','+row[ltlist[6]]+','+row[ltlist[7]]+','+row[ltlist[8]]+','+row[ltlist[9]]+
#                ','+row[ltlist[10]]+','+row[ltlist[11]]


with open('data2.csv','r',encoding='utf-8') as f:
    lines=f.readlines()
    print(lines)
    #lines[0].replace('\n','')

'''
newline=[]
with open('data2.csv','r',encoding='utf-8') as f:
    lines=f.readlines()
    for i in range(len(lines)):
        lines[i]=lines[i].replace('\n','')
        newline.append(lines[i])
        #print(line)
print('$'*30)
print(newline)

with open('data3.csv','w',encoding='utf-8') as f1:
    f1.writelines(newline)
'''

